var wsUri = "ws://localhost:9989/";

var activeTab;
var activeTabName;

var allDataElements = null;

$(document).ready(function()
{
    var activeTab = $("div.tab.active");
    var activeTabName = activeTab.attr('id');
    activeTab.show();
    
    // Handle changing tabs
    $('ul#topmenu > li').click(function()
    {
        clickedTab = $(this);
        if (clickedTab.attr('class') == "active")
        {
            return;
        }
        name = clickedTab.attr('id');
        $('ul#topmenu > li').attr("class", "");
        clickedTab.attr("class", "active");
        activeTab.hide();
        activeTab = $("div#" + name + "-tab");
        activeTabName = activeTab.attr('id');
        activeTab.show();
    });
    
    var websocket = new WebSocket(wsUri);
    websocket.onopen = function(evt) { 
        $("#status").attr("class", "connected");
        console.log("Connected");
    };
    websocket.onclose = function(evt) { 
        $("#status").attr("class", "disconnected");
        console.log("Disconnected");
    };
    websocket.onerror = function(evt) {
        console.log("WebSocket error: " + evt.data + "");
    };
    websocket.onmessage = function(evt) {
        var e = $.parseJSON(evt.data);

        if (e.type == "registers")
        {
            // Set speed and power
            speed = Math.round(e.data['FSN']['FSN_Speed'])
            voltage = e.data['MBN']['MBN_BMS_Voltage'];
            current = e.data['MBN']['MBN_BMS_Current'];
            power = Math.round((voltage * current) / 1000);
            
            $('div#speed > span').html(speed);
            $('div#power > span').html(power);
            
            if (activeTabName == "battery-tab")
            {
                $('#total-voltage').html(voltage);
                $('#total-current').html(current);
                $('#total-temperature').html(e.data['MBN']['MBN_BMS_Temperature'])
                $('#soc-value').html(e.data['MBN']['MBN_BMS_SOCHV']);
                
                dumps = [];
                dumps.push(e.data['MBN']['MBN_BMS_VoltageDump2']);
                dumps.push(e.data['MBN']['MBN_BMS_VoltageDump3']);
                dumps.push(e.data['MBN']['MBN_BMS_VoltageDump4']);
                dumps.push(e.data['MBN']['MBN_BMS_VoltageDump5']);
                dumps.push(e.data['MBN']['MBN_BMS_VoltageDump1']);

                bankNumber = 0;
                cellVoltages = [];

                $.each(dumps, function(i, dump)
                {
                    bytes = [];
                    bytes.push(parseInt(dump.slice(0, 8), 2));
                    bytes.push(parseInt(dump.slice(8, 16), 2));
                    bytes.push(parseInt(dump.slice(16, 24), 2));
                    bytes.push(parseInt(dump.slice(24, 32), 2));

                    if (i == 4) // Register Dump1
                    {
                        bankNumber = bytes[0];

                        if(bankNumber == 3 || bankNumber == 4)
                        {
                            cellVoltages.push(bytes[3] * 0.01 + 2);
                            cellVoltages.push(bytes[2] * 0.01 + 2);
                        }
                    }
                    else
                    {
                        $.each(bytes, function(j, bytex)
                        {
                            cellVoltages.push(bytex * 0.01 + 2);
                        });
                    }
                });

                chart = charts[bankNumber - 1];
                $.each(chart.series[0].points, function (i, point)
                {
                    point.update(cellVoltages[i], false);
                });
                chart.redraw();
            }
            else if (activeTabName == "alldata-tab")
            {
                if (allDataElements == null)
                {
                    registers = $('#registers');
                    // Initialize structure
                    allDataElements = {};
                    for (var node in e.data)
                    {
                        if (e.data.hasOwnProperty(node))
                        {
                            // Add new node to HTML file
                            html = "<div><h2>" + node + "</h2>";
                            allDataElements[node] = {};
                            for (var register in e.data[node])
                            {
                                if (e.data.hasOwnProperty(node))
                                {
                                    html += "<b>" + register
                                        + ":</b> <span id='" + register + "'>"
                                        + e.data[node][register] + "</span><br/>";
                                }
                            }
                            html += "</div>";
                            registers.append(html);
                            for (var register in e.data[node])
                            {
                                if (e.data.hasOwnProperty(node))
                                {
                                    allDataElements[node][register] = $("#" + register);
                                }
                            }
                        }
                    }
                }
                else
                {
                    // Elements were already displayed, update them
                    for (var node in e.data)
                    {
                        if (e.data.hasOwnProperty(node))
                        {
                            for (var register in e.data[node])
                            {
                                if (e.data.hasOwnProperty(node))
                                {
                                    allDataElements[node][register].html(e.data[node][register]);
                                }
                            }
                        }
                    }
                }
            }
            
        }
        else
        {
            console.log("type: " + evt.type);
        }

    };
});

//$(document).ready(function(){
//    output = $("#output");
//    registers = $("#registers")
//
//    var websocket = new WebSocket(wsUri);
//    websocket.onopen = function(evt) { 
//        output.html(output.html() + "Connected<br/>")
//    };
//    websocket.onclose = function(evt) { 
//        output.html(output.html() + "Disconnected<br/>")
//    };
//    websocket.onerror = function(evt) {
//        output.html(output.html() + "Error " + evt.data + "<br/>")
//    };
//    websocket.onmessage = function(evt) {
//        var e = $.parseJSON(evt.data);
//
//        if (e.type == "registers")
//        {
//            output.html(e);
//            if (elements == null)
//            {
//                // Initialize structure
//                elements = {};
//                for (var node in e.data)
//                {
//                    if (e.data.hasOwnProperty(node))
//                    {
//                        // Add new node to HTML file
//                        registers.append("<h2>" + node + "</h2>");
//                        elements[node] = {};
//                        for (var register in e.data[node])
//                        {
//                            if (e.data.hasOwnProperty(node))
//                            {
//                                registers.append("<b>" + register
//                                    + ":</b> <span id='" + register + "'>"
//                                    + e.data[node][register] + "</span><br/>");
//                                elements[node][register] = $("#" + register);
//                            }
//                        }
//                    }
//                }
//            }
//            else
//            {
//                // Elements were already displayed, update them
//                for (var node in e.data)
//                {
//                    if (e.data.hasOwnProperty(node))
//                    {
//                        for (var register in e.data[node])
//                        {
//                            if (e.data.hasOwnProperty(node))
//                            {
//                                elements[node][register].html(e.data[node][register]);
//                            }
//                        }
//                    }
//                }
//            }
//        }
//        else
//        {
//            console.log("type: " + evt.type);
//        }
//
//    };
//});